<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>复盘</title>
</head>

<link type="text/css" rel="stylesheet" href="{{ url_for('static', filename='css/fupan_css.css') }}" />
<link rel="stylesheet" href="http://js.jrj.com.cn/lib/ui/calendar.css" />
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
<script src="{{ url_for('static',filename='js/jquery-2.1.1.min.js') }}"></script>
<script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/jquery.tablesorter/2.9.1/jquery.tablesorter.min.js"></script>
<script type="text/javascript">
    $(function() {
        $("#mytable").tablesorter();
    });
</script>

<body>
    <div class="table-one" align="center">
        <label for="meeting">复盘日期:</label>
        <input id="meeting" type="date" value="2022-01-03" onchange="upperCase(this.id)" />
        <label>次日赚钱效应:</label>
        <select id="select" onchange="getSelectValue(this)"></select>
        <table id="mytable" cellspacing="0" cellpadding="0" border="0"></table>
    </div>

    <script>
        // 历史回溯

        // 获取下拉列表的值
        function getSelectValue(obj) {
            // var sValue = obj.options[obj.options.selectedIndex].value; //这是取值
            var text = obj.options[obj.options.selectedIndex].innerHTML; //这是取文本内容
            selectedIndex = obj.options.selectedIndex - 1 //选择后的索引
            if (selectedIndex >= 0) {
                var text_next = obj.options[selectedIndex].innerHTML; //这是取文本内容
            }

            search(text + '收盘价 ' + text_next + '开盘价 ' + text_next + '收盘价 ' + text_next + '涨停价 ' + text_next + '跌停价 ', text, text_next) //根据时间获取数据
        }

        //设置下拉列表
        function setSelect(date) {
            et = document.getElementById("select")
            et.innerHTML = ''
            for (var i = 0; i < date.length; i++) {
                et.innerHTML += '<option>' + date[i] + '</option>'
            }

        }

        //问财搜索
        function search(search, date1, date2) {
            var m_data = []
            $.ajax({
                url: '/searchWencai',
                data: {
                    'data': search
                },
                type: 'POST',
                async: false,
                dataType: 'json',
                success: function(data) {
                    m_data = data;
                    data = decode_search_data(data, date1, date2)
                    update_table_wencai(data)
                },
                error: function(msg) {
                    console.log(msg);
                }
            })
        };

        //解析数据
        function decode_search_data(data, date1, date2) {
            data = data['data']
            code = data['columns'].indexOf('code')
            last_close = data['columns'].indexOf('收盘价:不复权[' + date1.replaceAll('-', '') + ']') //昨日收盘价
            _close = data['columns'].indexOf('收盘价:不复权[' + date2.replaceAll('-', '') + ']') //选定日收盘价
            _open = data['columns'].indexOf('开盘价:不复权[' + date2.replaceAll('-', '') + ']') //开盘价
            raising_limit = data['columns'].indexOf('涨停价[' + date2.replaceAll('-', '') + ']') //涨停价
            limit_down = data['columns'].indexOf('跌停价[' + date2.replaceAll('-', '') + ']') //跌停价

            r_data = {}
            for (var i = 0; i < data['data'].length; i++) {
                var _data = []
                _data.push(data['data'][i][last_close])
                _data.push(data['data'][i][_close])
                _data.push(data['data'][i][_open])
                _data.push(data['data'][i][raising_limit])
                _data.push(data['data'][i][limit_down])
                r_data[data['data'][i][code]] = _data
            }
            return r_data
        }
    </script>
    <!-- 日期事件 -->
    <script type="text/javascript">
        function upperCase(x) {
            // 选择日期后停止运行刷新
            if (ID_THREAD != -1) {
                clearInterval(ID_THREAD)
            }

            var y = document.getElementById(x).value
            document.getElementById(x).value = y.toUpperCase()
                // alert(x);
                // alert(y.toUpperCase());
            document.getElementById("mytable").innerHTML = ''; //获取表格的dom节点
            var m_codes = show_excel(y.toUpperCase()); //显示表格内容并返回表格内的股票代码
            setSelect(m_codes['date']) //设置下拉列表
            codes = m_codes['codes']
            get_rise_data(codes)

            // 如果今天开盘则更新表格
            if (get_date() == get_kpl_date()['date']) {
                ID_THREAD = setInterval('is_running()', 1000 * 3); //指定3秒刷新一次
            }
        }
    </script>

    <script type="text/javascript">
        var ID_THREAD = -1 //循环线程
        var codes = []
        var last_date = get_last_date()['date']
            // 发送ajax请求，从后台获取json数据
        $(document).ready(function() {
            set_date()
            var m_codes = show_excel()
            setSelect(m_codes['date']) //设置下拉列表
            codes = m_codes['codes']
            auto_update(codes)
            get_rise_data(codes)
        });

        // 设置日期
        function set_date() {
            date = document.getElementById("meeting"); //获取表格的dom节点
            date.value = last_date
        }

        //show the excel
        function show_excel(date = last_date) {
            var tb = document.getElementById("mytable"); //获取表格的dom节点
            var data = get_data(date);
            var row = 0;
            var data_length = data['data'].length
            var codes = new Array();
            var row_date = 9 //日期列数
            var column_date = 1 //日期行数
            var date = new Array() //excel内的日期
            for (var column = 0; column < data_length; column++) {
                var x = tb.insertRow(column); //插入一行
                //设置class
                if (column % 2 != 0) {
                    x.className = "cur";
                }
                var m_rows = data['data'][column];
                for (var row = 0; row < m_rows.length; row++) {
                    if (row >= row_date && column == column_date) { //保存日期
                        date.push(data['data'][column][row]['data'])
                    }
                    var y = x.insertCell(row); //插入一个单元格
                    // if (data['data'][column][row]['data'] == null && row != 0) {
                    if (data['data'][column][row]['span']) {
                        // tb.rows[column].deleteCell(row);
                        tb.rows[column].cells[row].colSpan = data['data'][column][row]['span']; //合并单元格
                        y.innerHTML = data['data'][column][row]['data'] //填充数据
                        break;
                    }
                    y.innerHTML = data['data'][column][row]['data'] //填充数据
                    if (row == 1) {
                        if (!isNaN(data['data'][column][row]['data']) && data['data'][column][row]['data'] != null) {
                            codes.push((data['data'][column][row]['data']).toString()) //获取股票代码
                        }
                    }
                    if (data['data'][column][row]['color'].length > 6) {
                        y.style.color = '#' + data['data'][column][row]['color'].slice(-6) //设置字体颜色
                    }

                    // console.log(data['data'][column][row]['background_color'])
                    if (data['data'][column][row]['background_color'].length > 6) {
                        y.style.background = '#' + data['data'][column][row]['background_color'].slice(-6) //设置背景颜色
                    }
                }

            }
            return {
                codes,
                date
            };
        }

        function is_running() {
            console.log('while runing 3s')
            if (get_time()) {
                get_rise_data(codes);
            } else {
                if (ID_THREAD != -1) {
                    clearInterval(ID_THREAD)
                }
            }
        }

        function get_time() {
            //获取当前时间
            var d = new Date();
            var m_date = d.getHours() + "-" + d.getMinutes() + "-" + d.getSeconds();
            // return m_date;
            // 判断时间是否在开盘时间段
            if ((15 * 60 * 60) > (d.getHours() * 60 * 60 + d.getMinutes() * 60 + d.getSeconds()) && (d.getHours() * 60 * 60 + d.getMinutes() * 60 + d.getSeconds()) > (9 * 60 * 60 + 15 * 60)) {
                return true
            } else {
                return false
            }
        }

        function auto_update(codes) {
            // data = get_time();
            if (get_date() == get_kpl_date()['date']) {
                ID_THREAD = setInterval('is_running()', 1000 * 3); //指定3秒刷新一次
            } else {
                if (ID_THREAD != -1) {
                    clearInterval(ID_THREAD)
                }
            }
        }

        function get_date() {
            //获取当前日期
            var d = new Date();
            var m_date = d.getFullYear() + "-" + formatZero(String(parseInt(d.getMonth()) + 1)) + "-" + formatZero(d.getDate());
            return m_date;
        }

        //格式化日期时间
        function formatZero(n) {
            if (n >= 0 && n <= 9) {
                return "0" + n;
            } else {
                return n;
            }
        }

        //kaipanla date
        function get_kpl_date() {
            var m_data = []
            $.ajax({
                url: '/now_date',
                data: {},
                type: 'POST',
                async: false,
                dataType: 'json',
                success: function(data) {
                    m_data = data;
                },
                error: function(msg) {
                    console.log(msg);
                }
            })
            return m_data;
        };

        // get the date from excel
        function get_data(m_date = last_date) {
            var m_data = []
            $.ajax({
                url: '/fupan_call_back',
                data: {
                    date: m_date
                },
                type: 'POST',
                async: false,
                dataType: 'json',
                success: function(data) {
                    // console.log(data);
                    m_data = data;
                },
                error: function(msg) {
                    console.log(msg);
                }
            })
            return m_data;
        };

        //更新表格内的数据
        function update_table_wencai(data) {
            var tb = document.getElementById("mytable"); //获取表格的dom节点
            var rose = 7; //涨幅列数
            var rose_start = 6; //开盘涨幅列数
            var rose_all = 8; //实体涨幅
            var row = 0;
            var data_length = data.length
            var codes = new Array();
            for (var row = 1; row < tb.rows.length; row++) {
                var code = tb.rows[row].cells[1]
                var m_code = code.innerHTML
                if (!isNaN(m_code) && m_code != null) {
                    // console.log(data[code.innerHTML]['涨跌(%)'])
                    _open = ((parseFloat(data[m_code][2]) - parseFloat(data[m_code][0])) / parseFloat(data[m_code][0]) * 100).toFixed(2) //开盘涨幅
                    _close = ((parseFloat(data[m_code][1]) - parseFloat(data[m_code][0])) / parseFloat(data[m_code][0]) * 100).toFixed(2) //收盘涨幅
                    raise = _close - _open //实体涨幅
                    raising_limit = parseFloat(data[m_code][3]).toFixed(2) //涨停价
                    tb.rows[row].cells[rose_start].innerHTML = _open
                    tb.rows[row].cells[rose].innerHTML = _close
                    tb.rows[row].cells[rose_all].innerHTML = raise.toFixed(2)

                    //设置字体颜色
                    if (_open > 0) {
                        tb.rows[row].cells[rose_start].style.color = "#ff0000"; //红色
                    } else if (_open < 0) {
                        tb.rows[row].cells[rose_start].style.color = "#00c800"; //绿色
                    } else {
                        tb.rows[row].cells[rose_start].style.color = "#000000"; //黑色
                    }
                    if (_close > 0) {
                        tb.rows[row].cells[rose].style.color = "#ff0000"; //红色
                    } else if (_close < 0) {
                        tb.rows[row].cells[rose].style.color = "#00c800"; //绿色
                    } else {
                        tb.rows[row].cells[rose].style.color = "#000000"; //黑色
                    }
                    if (raise > 0) {
                        tb.rows[row].cells[rose_all].style.color = "#ff0000"; //红色
                    } else if (raise < 0) {
                        tb.rows[row].cells[rose_all].style.color = "#00c800"; //绿色
                    } else {
                        tb.rows[row].cells[rose_all].style.color = "#000000"; //黑色
                    }

                    //设置涨停背景颜色
                    if (parseFloat(data[m_code][1]) == parseFloat(data[m_code][3])) {
                        tb.rows[row].cells[rose].style.background = "#fa4949";
                        tb.rows[row].cells[rose].style.color = "#ffffff";
                    } else if (parseFloat(data[m_code][1]) == parseFloat(data[m_code][4])) {
                        tb.rows[row].cells[rose].style.background = "#00c800";
                        tb.rows[row].cells[rose].style.color = "#ffffff";
                    } else {
                        tb.rows[row].cells[rose].style.background = "#ffffff";
                    }
                    if (parseFloat(data[m_code][2]) == parseFloat(data[m_code][3])) {
                        tb.rows[row].cells[rose_start].style.background = "#fa4949";
                        tb.rows[row].cells[rose_start].style.color = "#ffffff";
                    } else if (parseFloat(data[m_code][2]) == parseFloat(data[m_code][4])) {
                        tb.rows[row].cells[rose_start].style.background = "#00c800";
                        tb.rows[row].cells[rose_start].style.color = "#ffffff";
                    } else {
                        tb.rows[row].cells[rose_start].style.background = "#ffffff";
                    }


                }
            }
        }

        //更新表格内的数据
        function update_table(data) {
            var tb = document.getElementById("mytable"); //获取表格的dom节点
            var rose = 7; //涨幅列数
            var rose_start = 6; //开盘涨幅列数
            var rose_all = 8; //实体涨幅
            var row = 0;
            var data_length = data.length
            var codes = new Array();
            for (var row = 1; row < tb.rows.length; row++) {
                var code = tb.rows[row].cells[1]
                var m_code = code.innerHTML
                if (!isNaN(m_code) && m_code != null) {
                    // console.log(data[code.innerHTML]['涨跌(%)'])
                    tb.rows[row].cells[rose].innerHTML = data[m_code]['涨跌(%)']
                    tb.rows[row].cells[rose_start].innerHTML = (((data[m_code]['open'] - data[m_code]['close']) / data[m_code]['close']) * 100).toFixed(2)
                    tb.rows[row].cells[rose_all].innerHTML = (((data[m_code]['now'] - data[m_code]['open']) / data[m_code]['close']) * 100).toFixed(2)

                    //设置字体颜色
                    if (data[code.innerHTML]['涨跌(%)'] > 0) {
                        tb.rows[row].cells[rose].style.color = "#ff0000"; //红色
                    } else if (data[code.innerHTML]['涨跌(%)'] < 0) {
                        tb.rows[row].cells[rose].style.color = "#00c800"; //绿色
                    }
                    if (data[m_code]['open'] - data[m_code]['close'] > 0) {
                        tb.rows[row].cells[rose_start].style.color = "#ff0000"; //红色
                    } else if (data[m_code]['open'] - data[m_code]['close'] < 0) {
                        tb.rows[row].cells[rose_start].style.color = "#00c800"; //绿色
                    }
                    if (data[m_code]['now'] - data[m_code]['open'] > 0) {
                        tb.rows[row].cells[rose_all].style.color = "#ff0000"; //红色
                    } else if (data[m_code]['now'] - data[m_code]['open'] < 0) {
                        tb.rows[row].cells[rose_all].style.color = "#00c800"; //绿色
                    }

                    //设置涨停背景颜色
                    if (data[code.innerHTML]['涨停价'] == data[code.innerHTML]['now'] && data[code.innerHTML]['ask1'] == 0) {
                        tb.rows[row].cells[rose].style.background = "#fa4949";
                        tb.rows[row].cells[rose].style.color = "#ffffff";
                    } else if (data[code.innerHTML]['跌停价'] == data[code.innerHTML]['now'] && data[code.innerHTML]['bid1'] == 0) {
                        tb.rows[row].cells[rose].style.background = "#00c800";
                        tb.rows[row].cells[rose].style.color = "#ffffff";
                    }
                    if (data[code.innerHTML]['涨停价'] == data[code.innerHTML]['open']) {
                        tb.rows[row].cells[rose_start].style.background = "#fa4949";
                        tb.rows[row].cells[rose_start].style.color = "#ffffff";
                    } else if (data[code.innerHTML]['跌停价'] == data[code.innerHTML]['open']) {
                        tb.rows[row].cells[rose_start].style.background = "#00c800";
                        tb.rows[row].cells[rose_start].style.color = "#ffffff";
                    }
                    // if (data[code.innerHTML]['涨停价'] == data[code.innerHTML]['now'] && data[code.innerHTML]['ask1'] == 0) {
                    //     tb.rows[row].cells[rose_all].className = "rbnews";
                    // } else if (data[code.innerHTML]['跌停价'] == data[code.innerHTML]['now'] && data[code.innerHTML]['bid1'] == 0) {
                    //     tb.rows[row].cells[rose_all].className = "gbnews";
                    // }

                }
            }
        }

        // 获取股票涨幅数据
        function get_rise_data(codes) {
            var m_data = []
            $.ajax({
                url: '/codes_rise',
                data: JSON.stringify({
                    data: codes
                }),
                type: 'POST',
                async: true, //异步加载
                dataType: 'json',
                contentType: 'application/json; charset=UTF-8',
                success: function(data) {
                    m_data = data;
                    update_table(data)
                },
                error: function(msg) {
                    console.log(msg);
                }
            })
            return m_data;
        };

        // 获取股票历史涨幅数据
        function px_change_rate(code, date) {
            var m_data = []
            $.ajax({
                url: '/px_change_rate',
                data: JSON.stringify({
                    code: code,
                    date: date
                }),
                type: 'POST',
                async: false,
                dataType: 'json',
                contentType: 'application/json; charset=UTF-8',
                success: function(data) {
                    m_data = data['data'];
                    // update_table(data)
                },
                error: function(msg) {
                    console.log(msg);
                }
            })
            return m_data;
        };

        // 获取上个交易日日期
        function get_last_date() {
            var m_data = []
            $.ajax({
                url: '/last_date',
                data: {},
                type: 'POST',
                async: false,
                dataType: 'json',
                // contentType: 'application/json; charset=UTF-8',
                success: function(data) {
                    m_data = data;
                    console.log(data);
                    // update_table(data)
                },
                error: function(msg) {
                    console.log(msg);
                }
            })
            return m_data;
        };

        // 获取最近几个交易日日期
        function get_history_date() {
            var m_data = []
            $.ajax({
                url: '/history_date',
                data: {},
                type: 'POST',
                async: false,
                dataType: 'json',
                // contentType: 'application/json; charset=UTF-8',
                success: function(data) {
                    m_data = data['date'];
                    console.log(data);
                    // update_table(data)
                },
                error: function(msg) {
                    console.log(msg);
                }
            })
            return m_data;
        };
    </script>
</body>

</html>